<template>
  <div class="title">AI 健康管理</div>
  <div class="subtitle">轻量化、智能化的健康伙伴</div>
  <form class="flip-card__form" @submit.prevent="handleLogin">
    <input v-model="loginForm.email" class="flip-card__input" placeholder="请输入您的邮箱" type="email" required>
    <div class="password-wrapper">
      <input v-model="loginForm.password" class="flip-card__input" placeholder="请输入您的密码" :type="showLoginPassword ? 'text' : 'password'" required>
      <button type="button" class="eye-button" @click="showLoginPassword = !showLoginPassword">
        {{ showLoginPassword ? '👁️' : '👁️‍🗨️' }}
      </button>
    </div>
    <button class="flip-card__btn" type="submit" :disabled="loading">
      {{ loading ? '登录中...' : '登 录' }}
    </button>
  </form>
</template>

<script setup>
import { reactive, ref, defineEmits } from 'vue';
import { useRouter } from 'vue-router';
import Request from '../utils/Request.js';
import { setToken } from '../utils/Storage.js';
import { useNotificationStore } from '@/stores/notification.js';

const emit = defineEmits(['update:loading']);
const router = useRouter();
const notificationStore = useNotificationStore();

const showLoginPassword = ref(false);
const loading = ref(false);
const loginForm = reactive({
  email: '',
  password: '',
});

const handleLogin = () => {
  if (!loginForm.email || !loginForm.password) return;
  loading.value = true;
  emit('update:loading', true);

  Request.postWithoutToken('/auth/login', loginForm)
      .then(response => {
        const { data: loginResult } = response;
        let token = loginResult?.token || (typeof loginResult === 'string' ? loginResult : null);

        if (token) {
          setToken(token);
          notificationStore.success('登录成功，正在跳转...');
          router.push({ name: 'Dashboard' });
        } else {
          // 如果后端成功返回但没有token，也视为一种错误
          Promise.reject('未能获取有效的认证信息');
        }
      })
      .catch(error => {
        console.error('登录失败:', error);
        // 错误提示已在Request拦截器中统一处理
      })
      .finally(() => {
        loading.value = false;
        emit('update:loading', false);
      });
};
</script>